﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Caching.Distributed;
using MQTTnet.Client.Subscribing;
using Newtonsoft.Json;
using System.Text;
using MQTTnet;
using Video.BackgroundServices.BusinessInterface;
using Video.BackgroundServices;
using Video.BackgroundServices.Utility.Dtos;

namespace PHMEE.BackgroundServices.Videos
{
    /// <summary>
    /// 配合张工实现视频播放
    /// </summary>
    public class VideoControlsWorker : BackgroundService
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<VideoControlsWorker> _logger;
        private readonly IMqttExtendManager _mqttExtendManager;
        private readonly IDistributedCache _distributedCache;
        private readonly string Topic;

        public VideoControlsWorker(IConfiguration configuration, ILogger<VideoControlsWorker> logger, IMqttExtendManager mqttExtendManager, IDistributedCache distributedCache)
        {
            _configuration = configuration;
            _logger = logger;
            _mqttExtendManager = mqttExtendManager;
            _distributedCache = distributedCache;
            Topic = _configuration.GetValue<string>("VidioClient:Topic")!;
        }

        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            // 使用 MqttExtendManager 来订阅主题并设置消息处理逻辑
            await _mqttExtendManager.SubscribeAsync(Topic, HandelDataAsync);

            await base.StartAsync(cancellationToken);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(5000, stoppingToken);
            }
        }

        private async Task HandelDataAsync(string requestInfo)
        {
            try
            {
                if (!string.IsNullOrEmpty(requestInfo))
                {
                    VideoResControlDto videoDatas = JsonConvert.DeserializeObject<VideoResControlDto>(requestInfo)!;

                    if (videoDatas != null)
                    {
                        // 播放视频
                        if (videoDatas.Action == VideoActionEnum.videoPlay)
                        {
                            await _distributedCache.SetStringAsync("videoPlay", requestInfo, new DistributedCacheEntryOptions
                            {
                                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5)
                            });
                        }
                        // 停止播放
                        else if (videoDatas.Action == VideoActionEnum.videoStop)
                        {
                            await _distributedCache.SetStringAsync("videoStop", requestInfo, new DistributedCacheEntryOptions
                            {
                                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5)
                            });
                        }
                        // 心跳监测
                        else if (videoDatas.Action == VideoActionEnum.videoOnline)
                        {
                            await _distributedCache.SetStringAsync("videoOnline", requestInfo, new DistributedCacheEntryOptions
                            {
                                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5)
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
            }
            await Task.CompletedTask;
        }
    }
}
